package com.systemCapacity.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.systemCapacity.common.dto.*;
import com.systemCapacity.entity.BattleCapacity;
import com.systemCapacity.entity.Enum.TemplateType;
import com.systemCapacity.mapper.BattleCapacityMapper;
import com.systemCapacity.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class BattleCapacityServiceImpl extends ServiceImpl<BattleCapacityMapper, BattleCapacity>
        implements BattleCapacityService {

    // 能力评估表头数量
    private static final int EVALUATE_SIZE = 12;

    @Autowired
    BattleCapacityMapper battleCapacityMapper;

    @Autowired
    EquipmentTemplateService equipmentTemplateService;

    /**
     * 查找作战能力
     * @param type 十大能力类型
     * @param firstName 能力首字母
     * @return 作战能力列表
     */
    @Override
    public List<BattleCapacityDto> getBattleCapacities(int type, String firstName) {
        // 查询一级能力
        QueryWrapper<BattleCapacity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("capacityType", type);
        // 设置无父节点，用空字符串表示
        queryWrapper.and(x -> x.isNull("pid")
                        .or()
                        .eq("pid",""));

        if (firstName != null && !firstName.isEmpty()) {
            queryWrapper.like("capacityName", firstName);
        }
        queryWrapper.orderByAsc("capacityType");
        List<BattleCapacity> firstCapacities = battleCapacityMapper.selectList(queryWrapper);
        List<BattleCapacityDto> battleCapacityDtos = new ArrayList<>();

        for (BattleCapacity capacity : firstCapacities) {
            BattleCapacityDto dto = BeanUtil.copyProperties(capacity, BattleCapacityDto.class);
            dto.setChildren(new ArrayList<>());
            // 查询子能力
            QueryWrapper<BattleCapacity> wrapper = new QueryWrapper<>();
            wrapper.eq("pid", capacity.getCapacityId());
            List<BattleCapacity> capacities = battleCapacityMapper.selectList(wrapper);
            for (BattleCapacity childCapacity : capacities) {
                BattleCapacityDto childDto = BeanUtil.copyProperties(childCapacity, BattleCapacityDto.class);
                dto.getChildren().add(childDto);
                childDto.setRelatedType(new ArrayList<>());
                if (StringUtils.isEmpty(childCapacity.getRelatedEquipmentType())) {
                    childDto.setRelatedTypes(new ArrayList<>());
                    continue;
                }
                String[] equipmentTypes = childCapacity.getRelatedEquipmentType().split(";");
                childDto.setRelatedTypes(Arrays.asList(equipmentTypes));
//                for (String equipmentType : equipmentTypes) {
//                    childDto.getRelatedType().add(TemplateType.values()[Integer.parseInt(equipmentType)]);
//                }
            }
            battleCapacityDtos.add(dto);
        }
        return battleCapacityDtos;
    }

    @Override
    @Transactional
    public boolean saveBattleCapacity(BattleCapacityDto dto) {
        // 添加一级能力
        if (dto.getPid() == null || dto.getPid().isEmpty()) {
            String capacityId = UUID.randomUUID().toString();
            dto.setCapacityId(capacityId);
            dto.setPid("");
            save(BeanUtil.copyProperties(dto, BattleCapacity.class));
            if (dto.getChildren() == null) {
                return true;
            }
            for (BattleCapacityDto childDto : dto.getChildren()) {
                childDto.setPid(capacityId);
                saveSecondCapacity(childDto);
            }
        } else {
            saveSecondCapacity(dto);
        }

        return true;
    }

    /**
     * 查看能力名称是否存在
     * @param capacityName 能力名称
     * @return 能力名称是否存在
     */
    @Override
    public boolean capacityNameExist(String capacityName) {
        QueryWrapper<BattleCapacity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("capacityName", capacityName);
        return getOne(queryWrapper) != null;
    }

    /**
     * 编辑作战能力
     * @param dto 作战能力传输类
     * @return 操作是否成功
     */
    @Override
    public boolean editBattleCapacity(BattleCapacityDto dto) {
        LambdaUpdateWrapper<BattleCapacity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(BattleCapacity::getCapacityId, dto.getCapacityId())
                .set(BattleCapacity::getCapacityName, dto.getCapacityName());
        if (dto.getPid() != null && !dto.getPid().isEmpty()) {
            StringBuilder typeStr= new StringBuilder();
            List<String> relatedTypes = dto.getRelatedTypes();
            for (String type : relatedTypes) {
                typeStr.append(type);
                typeStr.append(";");
            }
            typeStr.setLength(Math.max(typeStr.length() - 1, 0));
            lambdaUpdateWrapper.set(BattleCapacity::getRelatedEquipmentType, typeStr.toString());
        }
        update(lambdaUpdateWrapper);
        return false;
    }

    /**
     * 给定id判断作战能力是否存在
     * @param capacityId 能力id
     * @return 能力id是否存在
     */
    @Override
    public boolean capacityExist(String capacityId) {
        QueryWrapper<BattleCapacity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("capacityId", capacityId);
        return getOne(queryWrapper) != null;
    }

    /**
     * 搜索一级能力
     * @param type 十大能力类型
     * @param firstName 作战能力首字母
     * @return 一级能力列表
     */
    @Override
    public List<BattleCapacityDto> getFirstCapacities(int type, String firstName) {
        QueryWrapper<BattleCapacity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("capacityType", type);
        // 设置无父节点，用空字符串表示
        queryWrapper.eq("pid","");
        if (firstName != null && !firstName.isEmpty()) {
            queryWrapper.like("capacityName", firstName);
        }
        List<BattleCapacity> firstCapacities = battleCapacityMapper.selectList(queryWrapper);
        return firstCapacities.stream().map(capacity-> BeanUtil.copyProperties(capacity, BattleCapacityDto.class)).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public boolean saveRelatedTypes(List<CapacityRelatedTypesSaveDto> dtos) {
        dtos.forEach(dto -> {
            LambdaUpdateWrapper<BattleCapacity> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(BattleCapacity::getCapacityId, dto.getId());

            String types = dto.getTypes().stream().collect(Collectors.joining(";"));
            wrapper.set(BattleCapacity::getRelatedEquipmentType, types);
            update(wrapper);
        });
        return true;
    }

    /**
     * 保存二级能力
     * @param dto 作战能力传输类
     * @return 返回是否保存成功
     */
    private boolean saveSecondCapacity(BattleCapacityDto dto) {
        if (capacityNameExist(dto.getCapacityName())) {
            return false;
        }
        BattleCapacity battleCapacity = BeanUtil.copyProperties(dto, BattleCapacity.class);
        List<String> relatedTypes = dto.getRelatedTypes();
        StringBuilder typeBuilder = new StringBuilder();
        for (String type : relatedTypes) {
            typeBuilder.append(type);
            typeBuilder.append(";");
        }
        // 去除最后多余的';'
        typeBuilder.setLength(Math.max(typeBuilder.length() - 1, 0));
        battleCapacity.setRelatedEquipmentType(typeBuilder.toString());
        battleCapacity.setCapacityId(UUID.randomUUID().toString());
        save(battleCapacity);
        return true;
    }

    /**
     * 查询表头
     * @return
     */
    @Override
    public List<EquipmentTemplateDto> getTableColumnList(){
        List<EquipmentTemplateDto> equipmentTemplateDtoList = equipmentTemplateService.getRedPlatfomList();
        return equipmentTemplateDtoList;
    }

    @Override
    public List<BattleCapacityDto> queryCapacityListByType(String type){
        QueryWrapper<BattleCapacity> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("relatedEquipmentType",type);
        List<BattleCapacity> battleCapacityList = list(queryWrapper);
        List<BattleCapacityDto> battleCapacityDtoList = battleCapacityList.stream().map(x -> {
            BattleCapacityDto dto = new BattleCapacityDto();
            BeanUtils.copyProperties(x, dto);
            return dto;
        }).collect(Collectors.toList());
        return battleCapacityDtoList;
    }
}
